package com.cndw.kungfu.controller;

import java.util.HashMap;
import java.util.Map;

import com.cndw.commons.util.BlankUtils;
import com.cndw.kungfu.comm.tencent.LogFieldType;
import com.cndw.kungfu.comm.tencent.QQDC;
import com.cndw.kungfu.config.Constants;
import com.cndw.kungfu.config.ConstantsCost;
import com.cndw.kungfu.config.ConstantsIntKey;
import com.cndw.kungfu.config.ConstantsLog;
import com.cndw.kungfu.config.ConstantsModel;
import com.cndw.kungfu.config.ConstantsRadio;
import com.cndw.kungfu.config.GoodsEffectConfig;
import com.cndw.kungfu.domain.GoodsMode;
import com.cndw.kungfu.domain.Player;
import com.cndw.kungfu.domain.Scene;
import com.cndw.kungfu.domain.Union;
import com.cndw.kungfu.ext.LanguageLib;
import com.cndw.kungfu.ext.LogUtil;
import com.cndw.kungfu.ext.NumberProcesser;
import com.cndw.kungfu.ext.TimeProcesser;
import com.cndw.kungfu.model.ActivitySerialize;
import com.cndw.kungfu.model.Context;
import com.cndw.kungfu.model.battle.Battle;
import com.cndw.kungfu.model.battle.FighterMonster;
import com.cndw.kungfu.model.siege.domain.SiegePlayer;
import com.cndw.kungfu.model.siege.domain.SiegePlayerAwards;
import com.cndw.kungfu.model.siege.domain.SiegeWar;
import com.cndw.kungfu.model.sys.LogServer;
import com.cndw.kungfu.vo.EventNotice;
import com.cndw.rpg.annotation.Controller;
import com.cndw.rpg.framework.ResponseMessage;
import com.cndw.rpg.framework.Session;

/**
 * 围城控制器
 * 
 * 
 * @author <a href="mailto:whz-work@163.com">汪洪州</a>
 * 
 * @since 1.0 Create on 2011-8-27
 */
@Controller
public class SiegeController {

	/**
	 * 获取围城信息
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage getSiegeInfo(Session session) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("ranking", ActivitySerialize.getInstance().getSiegeRanking());

		// 是否可领取奖励
		boolean isGet = false;
		SiegePlayerAwards awards = SiegeWar.getPlayerawards().get(session.getUid());
		if (!BlankUtils.isBlank(awards)) {
			isGet = !awards.isGet();
		}
		resultMap.put("canGet", isGet);

		// 围城是否结束
		if (TimeProcesser.isRange(ConstantsModel.siegeWeek, ConstantsModel.siegeTime[1], ConstantsModel.siegeTime[2])) {
			resultMap.put("end", !SiegeWar.isBroadcast());
		}

		Union union = Context.getUnionServer().getUnionById(ActivitySerialize.getInstance().getSiegeUnionId()[0]);
		if (!BlankUtils.isBlank(union)) {
			resultMap.put("unionName", union.getName());
			resultMap.put("winCounts", ActivitySerialize.getInstance().getSiegeUnionId()[1]);
		}

		return ResponseMessage.getSuccMessage(resultMap);
	}

	/**
	 * 进入围城场景
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage intoSiege(Session session) {

		if (!TimeProcesser.isRange(ConstantsModel.siegeWeek, ConstantsModel.siegeTime[1], ConstantsModel.siegeTime[2])) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("siege.intoSiege.time"));// 非战斗时间
		}
		if (SiegeWar.getCurrentMonster() == null) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("siege.intoSiege.time"));// 非战斗时间
		}

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (!BlankUtils.isBlank(player.getTeam())) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("siege.intoSiege.team")); // 不能组队进入
		}

		Union union = Context.getUnionServer().getUnionByPlayerId(session.getUid());
		if (union == null) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("siege.apply.null"));
		}

		if (union.getLevel() < ConstantsModel.siegeUnionLevel) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("siege.apply.unionLevel", ConstantsModel.siegeUnionLevel)); // 帮派等级不够
		}
		
		if(TimeProcesser.getUnixTime() - player.getDataInfo().intDataGet(ConstantsIntKey.QUnionTime) < 90000) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("siege.intoSiege.forbid"));//退出帮派后，25小时限制进入围城战
		}

		Map<String, Object> resultMap = new HashMap<String, Object>();
		Scene scene = Context.getSceneServer().getSceneById(SiegeWar.getCurrentScene());
		union = Context.getUnionServer().getUnionById(ActivitySerialize.getInstance().getSiegeUnionId()[0]);
		if (!BlankUtils.isBlank(union) && union.getMemberIds().contains(player.getPlayerId())) {
			player.setTx(scene.getBirthPoint()[2] + NumberProcesser.mtRand(-150, -50));
			player.setTy(scene.getBirthPoint()[3] + NumberProcesser.mtRand(-100, 100));
			resultMap.put("attack", 0); // 非攻击方
		} else {
			player.setTx(scene.getBirthPoint()[0] + NumberProcesser.mtRand(150, 50));
			player.setTy(scene.getBirthPoint()[1] + NumberProcesser.mtRand(-100, 100));
			resultMap.put("attack", 1); // 攻击方
		}
		player.setTs(1); // 是否传送

		if (player.getSceneId() != ConstantsModel.siegeScene[0] && player.getSceneId() != ConstantsModel.siegeScene[1]) {
			player.getDataInfo().setLastSceneId(player.getSceneId());
		}

		SiegeWar.addJoinPlayers(player);
		
		player.getDataInfo().alterExpRet(Constants.expRet_unionBat);//参加活动标记

		int[] reviveInfo = SiegeWar.getPlayerReviveInfo(player.getPlayerId());
		resultMap.put("sceneId", scene.getId());
		resultMap.put("reviveTime", reviveInfo[0]);
		resultMap.put("reviveCounts", reviveInfo[1]);
		resultMap.put("buffAdd", reviveInfo[2]);
		resultMap.put("fatigue", reviveInfo[3]);
		resultMap.put("buffTimes", reviveInfo[4]);
		resultMap.put("soldiersBuff", SiegeWar.getSoldiersBuff());
		resultMap.put("rank", SiegeWar.getRanking(3));
		resultMap.put("endTime", SiegeWar.getEndTime());
		resultMap.put("monsterId", SiegeWar.getCurrentMonster().getSourceObject().getId());
		resultMap.put("hp", SiegeWar.getCurrentMonster().getHp());
		resultMap.put("maxHp", SiegeWar.getCurrentMonster().getMaxHp());
		resultMap.put("myRank", SiegeWar.getRanking().get(player.getUnionId()).clone());
		resultMap.put("unionRank", SiegeWar.getRanking().get(player.getUnionId()).getPlayers().values());
		resultMap.put("beginTime",
				SiegeWar.getCurrentScene() == ConstantsModel.siegeScene[0] ? SiegeWar.getBeginTime() + 60 : SiegeWar.getIntoSecondSceneTime());
		resultMap.put("defenceUnion", union != null ? union.getName() : null);

		QQDC.getInstance().logClick(player, LogFieldType.unionWar);

		return ResponseMessage.getSuccMessage(resultMap);
	}

	/**
	 * 点击拒马庄
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage getSiegePlayer(Session session) {

		if (SiegeWar.isCountDownTime()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("siege.getSiegePlayer.time"));
		}

		SiegePlayer siegePlayer = SiegeWar.getSiegePlayer(session.getUid());
		if (siegePlayer != null && !siegePlayer.isActive() && siegePlayer.getReviveTime() > TimeProcesser.getUnixTime()) {
			return ResponseMessage.getSuccMessage(siegePlayer.getReviveTime());
		}

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (player.getUnionId() == ActivitySerialize.getInstance().getSiegeUnionId()[0]) {
			if (SiegeWar.addSiegePlayers(player, false)) {
				SiegeWar.broadcastPlayer(player); // 广播告知加入防守
			}
		} else {
			SiegeWar.addSiegePlayers(player, true);
		}

		return ResponseMessage.getSuccMessage(SiegeWar.getSiegeActivePlayers());
	}

	/**
	 * 进入战斗
	 * 
	 * @param session
	 * @param targetId
	 * @return
	 */
	public ResponseMessage intoBattle(Session session, long targetId) {
		if (SiegeWar.isCountDownTime()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("siege.getSiegePlayer.time"));
		}
		if (targetId == session.getUid()) {
			return null;
		}

		SiegePlayer siegePlayer = SiegeWar.getSiegePlayer(session.getUid());
		SiegePlayer siegeTarget = SiegeWar.getSiegePlayer(targetId);
		if (siegePlayer == null || siegeTarget == null || siegePlayer.isDeath() || siegeTarget.isDeath()) {
			return null;
		}
		if (!siegePlayer.isAttack() || siegeTarget.isAttack()) {
			return null;
		}

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		Player target = Context.getPlayerServer().getByPlayerId(targetId);
		if (player.getUnionId() == 0 || target.getUnionId() ==0) {
			return null;
		}
		int sourceAdd = SiegeWar.getSoldiersBuff() + siegePlayer.getBuffAdd() - siegePlayer.getFatigue();
		if (sourceAdd < -100) {
			sourceAdd = -100;
		}
		int targetAdd = siegeTarget.getBuffAdd() - siegeTarget.getFatigue();
		Battle battle = new Battle(player.getLikedFighter(sourceAdd), target.getLikedFighter(targetAdd));
		battle.execBattle(Constants.battle_siege);
		battle.broadcast();
		battle.clear();
		// 更新疲劳值
		if (Math.abs(player.getLevel() - target.getLevel()) <= 15) {
			siegePlayer.alterFatigue(1);
			int oldfatigue = siegeTarget.getFatigue();
			siegeTarget.alterFatigue(1);
			if (oldfatigue != siegeTarget.getFatigue()) {
				EventNotice notice = new EventNotice(ConstantsRadio.siege, ConstantsRadio.siegefatigue);
				notice.put("fatigue", siegeTarget.getFatigue());
				notice.broadcast(siegeTarget.getPlayerId());
			}
		}

		if (battle.getWiner() == 1) {
			siegeTarget.killDeath(battle.getCostTime());
			SiegeWar.clacScore(player, target);
		} else {
			siegePlayer.killDeath(battle.getCostTime());
			SiegeWar.clacScore(target, player);
		}
		LogServer.recordLog(player, ConstantsLog.battle, 40025, target.getPlayerName(),SiegeWar.getPlayerScore(player),SiegeWar.getPlayerRanking(player));
		LogServer.recordLog(target, ConstantsLog.battle, 40025, player.getPlayerName(),SiegeWar.getPlayerScore(target),SiegeWar.getPlayerRanking(target));		
		QQDC.getInstance().logClick(player, LogFieldType.battleSiege);
		return ResponseMessage.getSuccMessage(siegePlayer.getFatigue());
	}

	/**
	 * 攻击据马庄或城墙
	 * 
	 * @param session
	 * @param barrierId
	 * @return
	 */
	public ResponseMessage attackBarrier(Session session, int barrierId) {
		if (SiegeWar.isCountDownTime()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("siege.getSiegePlayer.time"));
		}
		if (!SiegeWar.getSiegeActivePlayers().isEmpty()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("siege.err.haveplayer")); // 还有防守玩家
		}
		FighterMonster fighterTarget = SiegeWar.getCurrentMonster();
		if (fighterTarget == null || fighterTarget.getSourceObject().getId() != barrierId) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.args"));
		}
		SiegePlayer siegePlayer = SiegeWar.getSiegePlayer(session.getUid());
		if (siegePlayer == null || siegePlayer.isDeath() || !siegePlayer.isAttack()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("siege.err.player"));
		}
		int sourceAdd = SiegeWar.getSoldiersBuff() + siegePlayer.getBuffAdd() - siegePlayer.getFatigue();
		if (sourceAdd < -100) {
			sourceAdd = -100;
		}
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (player.getUnionId() == 0 ) {
			return null;
		}
		Battle battle = new Battle(player.getLikedFighter(sourceAdd), fighterTarget);
		battle.execBattle(Constants.battle_siege);
		battle.broadcast();
		battle.clear();
		try {
			SiegeWar.clacScore(player, battle.getSourceDam()); // 先计算积分
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		LogServer.recordLog(player, ConstantsLog.battle, 40025, fighterTarget.getName(),SiegeWar.getPlayerScore(player),SiegeWar.getPlayerRanking(player));

		if (battle.getWiner() == 1) {
			synchronized (SiegeWar.class) {
				if (SiegeWar.getCurrentScene() == ConstantsModel.siegeScene[0]) {
					SiegeWar.intoSecondScene(battle.getCostTime());
				} else {
					if (SiegeWar.getCurrentMonster() == null
							|| SiegeWar.getCurrentMonster().getSourceObject().getId() == fighterTarget.getSourceObject().getId()) {
						SiegeWar.closeWar(true);
					} else {
						LogUtil.getSystem().debug("siege concurrent err ...");
					}
				}
			}
		} else {
			siegePlayer.killDeath(battle.getCostTime());
		}
		QQDC.getInstance().logClick(player, LogFieldType.battleSiegeNpc);
		return ResponseMessage.getSuccMessage(true);
	}

	/**
	 * 玩家复活
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage revive(Session session) {
		SiegePlayer player = SiegeWar.getSiegePlayer(session.getUid());
		if (BlankUtils.isBlank(player)) {
			LogUtil.getMain().error("player don't join siege");
			return null;
		}

		if (!player.revive()) {// 日志写在了函数里面
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.gold"));
		}
		Player player2 = Context.getPlayerServer().getByPlayerId(session.getUid());
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("gold", player2.getGold());
		map.put("goldBing", player2.getGoldBing());
		return ResponseMessage.getSuccMessage(map);

	}

	/**
	 * 鼓舞
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage buff(Session session) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		
		Union union = Context.getUnionServer().getUnionByPlayerId(session.getUid());
		if (union == null) {
			return null;
		}

		if (union.getLevel() < ConstantsModel.siegeUnionLevel) {
			return null;
		}
		
		SiegeWar.addSiegeOnly(player);// 防止未创建就鼓舞
		SiegePlayer siegePlayer = SiegeWar.getSiegePlayer(session.getUid());

		if (siegePlayer == null) {
			return null;
		}

		int buffNow = siegePlayer.getBuffAdd();
		if (buffNow >= ConstantsModel.siegeBuffMax) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("siege.buff.max"));
		}
		boolean needCost = siegePlayer.getBuffTimes() > 0;
		int haveTool = player.getPlayerBoxs().getStackNum(GoodsEffectConfig.buffGoodsId);
		boolean costTool = needCost && haveTool > 0 ;
		if (needCost && !costTool && player.getGoldAll() < ConstantsModel.siegeBuffGold) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.gold"));
		} 
		if(needCost) {
			if (costTool) {
				player.getPlayerBoxs().costGoods(GoodsEffectConfig.buffGoodsId, 1);
				haveTool --;
			}else {
				player.alterGoldAll(-ConstantsModel.siegeBuffGold);
				player.commitSync();
				LogServer.costEventLog(session.getUid(), ConstantsModel.siegeBuffGold, ConstantsCost.siegeBuff);
			}
		}

		buffNow += ConstantsModel.siegeBuffAdd;
		siegePlayer.setBuffAdd(buffNow);
		siegePlayer.setBuffTimes(siegePlayer.getBuffTimes() + 1);
		
		EventNotice notice = new EventNotice(ConstantsRadio.battle, ConstantsRadio.battle_BuffAdd);
		notice.put("playerId", player.getPlayerId());
		notice.put("buffNow", buffNow);
		notice.broadcastScene(player);
		
		LogServer.recordLog(player, ConstantsLog.battle, 40023, needCost ? ConstantsModel.siegeBuffGold : 0, true, buffNow,costTool,haveTool);

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("gold", player.getGold());
		map.put("goldBing", player.getGoldBing());
		map.put("buffAdd", buffNow);
		map.put("suc", true);
		map.put("buffTimes", siegePlayer.getBuffTimes());
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 修正疲劳值
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage deFatigue(Session session) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		SiegePlayer siegePlayer = SiegeWar.getSiegePlayer(session.getUid());
		if (siegePlayer == null || siegePlayer.getFatigue() <= 40) {
			return null;
		}
		if (player.getGoldAll() < ConstantsModel.siegeDeBuffFixGold) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.gold"));
		}
		player.alterGoldAll(-ConstantsModel.siegeDeBuffFixGold);
		player.commitSync();

		siegePlayer.alterFatigue(-1);

		LogServer.costEventLog(session.getUid(), ConstantsModel.siegeDeBuffFixGold, ConstantsCost.siegeDeBuff);
		LogServer.recordLog(player, ConstantsLog.battle, 40024, ConstantsModel.siegeDeBuffFixGold, siegePlayer.getFatigue());

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("gold", player.getGold());
		map.put("goldBing", player.getGoldBing());
		map.put("fatigue", siegePlayer.getFatigue());
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 领取奖励
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage getAwards(Session session) {
		if (!SiegeWar.getPlayerawards().containsKey(session.getUid())) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("siege.getAwards.null"));
		}

		SiegePlayerAwards awards = SiegeWar.getPlayerawards().get(session.getUid());
		if (awards == null) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("siege.getAwards.null"));
		}

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (!BlankUtils.isBlank(awards.getGoods()) && !player.getPlayerBoxs().checkBlack(awards.getGoods().size())) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.player.boxmin", awards.getGoods().size()));
		}

		if (awards.checkGet()) { // 放在最后，会修改领取状态
			return ResponseMessage.ticpErrMsg(LanguageLib.get("siege.getAwards.checkGet"));
		}

		player.alterAsset(awards.getAsset());
		player.alterExp(awards.getExp());
		player.commitSync();

		// 增加个人贡献度，增加帮派资源
		Context.getUnionServer().addResource(player.getPlayerId(), awards.getResource(), 0, awards.getResource(), 0);

		// 给道具
		StringBuilder log = new StringBuilder();
		if (!BlankUtils.isBlank(awards.getGoods())) {
			GoodsMode mode;
			for (Object[] goods : awards.getGoods()) {
				int count = Integer.parseInt(goods[0].toString());
				mode = Context.getGoodsServer().getModeById(Integer.parseInt(goods[1].toString()));
				Context.getGoodsServer().giveGoodsBing(player.getPlayerId(), mode.getGoodsId(), count, Integer.parseInt(goods[3].toString()));
				log.append(mode.getName()).append("*").append(count);
			}
		}

		LogServer.recordLog(player, ConstantsLog.battle, 40022, awards.getAsset(), awards.getExp(), awards.getResource(), log.toString());

		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("exp", player.getExp());
		resultMap.put("asset", player.getAsset());
		return ResponseMessage.getSuccMessage(resultMap);
	}
}
